<script setup>
import { ref, onMounted,} from 'vue';
import request from '@/utils/request';
import { filemakerctrl, POBrowser } from 'js-pageoffice';

const titleText = ref('');
const selectAll = ref(false);
const isButtonDisabled=ref(false);
const files = ref([
  { id: 1, name: 'PageOffice产品简介', checked: false },
  { id: 2, name: 'PageOffice产品安装步骤', checked: false },
  { id: 3, name: 'PageOffice产品应用领域', checked: false },
  { id: 4, name: 'PageOffice产品对环境的要求', checked: false }
]);
const singleProgress = ref(0);
const overallProgress = ref(0);
const errorMsg = ref('');

onMounted(async () => {
  try {
    const response = await request({
      url: '/index',
      method: 'get',
    });
    titleText.value = response;
  } catch (error) {
    console.error('Failed to fetch title:', error);
  }
});

const toggleAllCheckboxes = () => {
  files.value.forEach(file => {
    file.checked = selectAll.value;
  });
};

const convertFiles = () => {
  const selectedFiles = files.value.filter(file => file.checked).map(file => file.id);

  if (selectedFiles.length === 0) {
    alert("请至少选择一个文档");
    return;
  }

  isButtonDisabled.value = true;//禁用按钮,防止重复点击

  convertFile(selectedFiles, 0);
};

const convertFile = (idArr, index) =>{
  // 设置用于保存文件的服务器端controller地址,该地址需从"/"开始，指向服务器端根目录  
  /** 如果想要给SaveFilePage传递多个参数，建议使用new URLSearchParams方式，例如：
* let saveFileUrl = "/FileMaker/save";
* let paramValue = new URLSearchParams({id:1,name:"张三"});
* filemakerctrl.SaveFilePage = `${saveFileUrl}?${paramValue.toString()}`;
*/
  filemakerctrl.SaveFilePage = "/FileMakerConvertPDFs/save?id=" + idArr[index];
  filemakerctrl.CallFileMaker({
    // url：指向服务器端FileMakerCtrl打开文件的controller地址，该地址需从"/"开始，指向服务器端根目录  
    url: "/FileMakerConvertPDFs/convert?id=" + idArr[index],
    success: (res) => {//res:获取服务器端fs.setCustomSaveResult设置的保存结果
      console.log(res);
      console.log("completed successfully.");
      setProgress1(100);
      index++;
      setProgress2(index, idArr.length);
      if (index < idArr.length) { //当下标小于数组长度，继续执行循环，继续转换下一个文件，这样形成递归循环调用
        convertFile(idArr, index);
      }else {
        isButtonDisabled.value = false;  // 所有文件转换完毕后启用按钮
      }
    },
    progress: (pos) => {
      console.log("running " + pos + "%");
      setProgress1(pos);
    },
    error: (msg) => {
       errorMsg.value  =
        "发生错误:" + msg;
      console.log("error occurred: " + msg);

      isButtonDisabled.value = false;  // 发生错误后启用按钮
    },
  });
};

const setProgress1 = (percent) => {
  singleProgress.value = percent;
};

const setProgress2 = (index, count) => {
  overallProgress.value = Math.round((index / count) * 100);
};

const openPageOffice = (vuePageUrl, param) => {
  POBrowser.openWindow(vuePageUrl, 'width=1200px;height=800px;', param);
};
</script>

<template>
  <div class="Word">
    <div style="margin: 100px" align="center">
      <h2>演示：批量转PDF</h2>
      <div style="width: 600px; margin: 0 auto; font-size: 14px">
        <p style="text-align: left">
          操作说明：<br />
          1. 勾选下面的文件；<br />
          2. 点击“批量转换PDF文档”按钮；<br />
          3.生成完毕后，即可在“FileMakerConvertPDFs/doc”目录下看到批量生成的PDF文件。<br />
        </p>
      </div>
      <h3>文件列表</h3>
      <table id="table1">
        <thead>
          <tr>
            <th>
              <input name="checkAll" type="checkbox" v-model="selectAll" @change="toggleAllCheckboxes" />
            </th>
            <th>序号</th>
            <th>文件名</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in files" :key="index">
            <td><input name="check" type="checkbox" v-model="item.checked" /></td>
            <td>{{ index + 1 }}</td>
            <td>{{ item.name }}</td>
            <td>
              <a href="#" @click.prevent="openPageOffice('Edit', item.id)">编辑</a>
            </td>
          </tr>
        </tbody>
      </table>

      <input type="button" id="Button1" :disabled="isButtonDisabled" value="批量转换PDF文档" @click="convertFiles" />

      <div id="progressDiv">
        单文件进度：
        <div class="progressBarContainer">
          <div id="progressBar1" class="progressBar" :style="{ width: singleProgress + '%' }">{{ singleProgress }}%</div>
        </div>
        整体进度：
        <div class="progressBarContainer">
          <div id="progressBar2" class="progressBar" :style="{ width: overallProgress + '%' }">{{ overallProgress }}%</div>
        </div>
        <div id="errorMsg">{{ errorMsg }}</div>
      </div>
    </div>
  </div>
</template>

<style scoped>
h3 {
  display: block;
  font-size: 1.17em;
  margin-block-start: 1em;
  margin-block-end: 1em;
  margin-inline-start: 0px;
  margin-inline-end: 0px;
  font-weight: bold;
}

h2 {
  display: block;
  font-size: 1.5em;
  margin-block-start: 0.83em;
  margin-block-end: 0.83em;
  margin-inline-start: 0px;
  margin-inline-end: 0px;
  font-weight: bold;
}

table {
  border: solid 1px #ccc;
  width: 600px;
  margin: 20px;
}

th {
  border-bottom: solid 1px #ccc;
  text-align: left;
  padding: 5px;
}

td {
  padding: 5px;
}

.progressBarContainer {
  width: 100%;
  background-color: #eee;
  border-radius: 5px;
  padding: 3px;
  box-shadow: 2px 2px 3px 3px #ccc inset;
}

.progressBar {
  height: 20px;
  width: 0%;
  background-color: #1a73e8;
  border-radius: 5px;
  text-align: center;
  line-height: 20px;
  color: white;
}

#progressDiv {
  width: 400px;
  margin: 10px auto;
  text-align: left;
  font-size: 14px;
  border: solid 1px #1a73e8;
  padding: 10px 20px;
  color: #1a73e8;
}

#errorMsg {
  color: red;
}
</style>